//
//  HomeSearchViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2017/2/6.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "HomeSearchViewController.h"
#import "StarInfomationViewController.h"
#import "HistoryCell.h"
#import "SearchListCell.h"
#import "QZHSearchBar.h"
#import "SearchHeaderView.h"
#import "SearchlistModel.h"

@interface HomeSearchViewController ()<UICollectionViewDelegate,UICollectionViewDataSource
,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>{
    NSMutableArray *_searchArray;
}
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) HistoryCell *cell;
@property (nonatomic, strong) NSMutableArray *data;
@property (nonatomic, assign) BOOL is_Reload;
@property (nonatomic, strong) QZHSearchBar *bar;
@end

@implementation HomeSearchViewController
static NSString *historyCell = @"historyCell";
static NSString *searchListCell = @"searchListCell";
static NSString *searchHeaderView = @"searchHeaderView";


#pragma mark -- 搜索请求
- (void)searchRequestWithSearchkey:(NSString *)searchkey {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"content":searchkey
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kSearch];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            NSArray *array = responseObject[@"data"][@"list"];
            if (_searchArray.count > 0) {
                [_searchArray removeAllObjects];
            }
            if (!array.count) {
                [self showTitle:responseObject[@"data"][@"message"]];
            }
            for (NSDictionary *searchDict in array) {
                SearchlistModel *model = [[SearchlistModel alloc] initWithDict:searchDict];
                [_searchArray addObject:model];
            }
            [self.collectionView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

#pragma mark -- 关注请求
- (void)FocusRequestWithStarId:(NSString *)starId IndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"follow":starId
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kFocus];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            SearchListCell *cell = (SearchListCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
            if ([responseObject[@"data"][@"status"] intValue] == 20) { //取消关注
                [cell.focusBtn setTitle:@"+ 关注" forState:UIControlStateNormal];
                [cell.focusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                cell.focusBtn.backgroundColor = [UIColor colorWithHexString:@"04DD98"];
            } else {
                [cell.focusBtn setTitle:@"已关注" forState:UIControlStateNormal];
                [cell.focusBtn setTitleColor:[UIColor colorWithHexString:@"04DD98"] forState:UIControlStateNormal];
                cell.focusBtn.backgroundColor = [UIColor whiteColor];
            }
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}
#pragma mark -- lazy
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerNib:[UINib nibWithNibName:@"HistoryCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:historyCell];
        [_collectionView registerNib:[UINib nibWithNibName:@"SearchListCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:searchListCell];
        [_collectionView registerNib:[UINib nibWithNibName:@"SearchHeaderView" bundle:[NSBundle mainBundle]]  forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:searchHeaderView];
    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNav];

    [self setUpUI];
}

- (void)setNav {
    UIButton *cancleBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
    [cancleBtn addTarget:self action:@selector(SearchCancleClick:) forControlEvents:UIControlEventTouchUpInside];
    cancleBtn.titleLabel.font = UIFont(14);
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:cancleBtn];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    space.width = 15;
    [self.navigationItem setRightBarButtonItems:@[rightBtnItem,space]];
    self.navigationItem.leftBarButtonItems = nil;
    self.navigationItem.hidesBackButton = YES;
    
    
    QZHSearchBar * bar = [[QZHSearchBar alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH - cancleBtn.width , 30)];
    self.bar = bar;
    bar.delegate = self;
    bar.backgroundColor = [UIColor navagationBarColor];
    bar.layer.borderWidth = 0.5;
    bar.layer.borderColor = [UIColor mainColor].CGColor;
    bar.layer.cornerRadius  = 15;
    bar.clipsToBounds = YES;
    bar.returnKeyType = UIReturnKeySearch;
    bar.textColor = [UIColor whiteColor];
    bar.tintColor = [UIColor whiteColor];
    [bar setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    bar.placeholder = @"明星";
    bar.clearsOnBeginEditing = YES;
    bar.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.navigationItem.titleView = bar;
    self.is_Reload = YES;
}

#pragma mark -- setUpUI
- (void)setUpUI {
    self.view.backgroundColor = [UIColor whiteColor];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    _data = [NSMutableArray arrayWithArray:@[@"测试数据",@"云标签",@"历史记录",@"测试",@"妈妈说标题要长",@"机智的手哥"]];
    _searchArray = [NSMutableArray arrayWithCapacity:1];
}

#pragma mark -- 取消搜索
- (void)SearchCancleClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- collectionView Delegate Datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.is_Reload) {
        return _searchArray.count;
    }
    return _data.count;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (self.is_Reload) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return UIEdgeInsetsMake(15, 15, 15, 15);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.is_Reload) {
        SearchListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:searchListCell forIndexPath:indexPath];
        SearchlistModel *model = _searchArray[indexPath.row];
        cell.searchModel = model;
        cell.focusAction = ^(){
            [self FocusRequestWithStarId:model.suid IndexPath:indexPath];
        };
        return cell;
    }
    HistoryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:historyCell forIndexPath:indexPath];
    cell.keyWord = self.data[indexPath.row];
    return cell;
}


//这个也是最重要的方法 获取Header的 方法。
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (self.is_Reload) {
        return nil;
    }
    //从缓存中获取 Headercell
    SearchHeaderView *cell = (SearchHeaderView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:searchHeaderView forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.titleLabel.text = @"搜索历史";
    } else {
        cell.titleLabel.text = @"热门搜索";
    }
    return cell;
}

#pragma mark -- UICollectionViewDelegateFlowLayout

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    if (self.is_Reload) {
        return 0;
    }
    return 5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    if (self.is_Reload) {
        return 0;
    }
    return 5;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchlistModel *model = _searchArray[indexPath.row];
    StarInfomationViewController *infoVC = [[StarInfomationViewController alloc] init];
    infoVC.s_uid = model.suid;
    [self.navigationController pushViewController:infoVC animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeZero;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (self.is_Reload) {
        return CGSizeMake(0, 0);
    }
    return CGSizeMake(kSCREEN_WIDTH, 40);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.is_Reload) {
        return CGSizeMake(kSCREEN_WIDTH, 70);
    }
    if (self.cell == nil) {
        self.cell = [[NSBundle mainBundle]loadNibNamed:@"HistoryCell" owner:nil options:nil][0];
    }
    self.cell.keyWord = _data[indexPath.row];
    return [self.cell sizeForCell];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length) {
        [self searchRequestWithSearchkey:textField.text];
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
